<template>
	<view class="bottom-bar">
		<!-- 左边功能按钮 -->
		<view class="left-icons">
			<!-- <view class="icon-item" @click="onService">
				<u-icon name="server-fill" size="22" color="#333"></u-icon>
				<text class="icon-text">客服</text>
			</view>
			<view class="icon-item" @click="onShop">
				<u-icon name="home-fill" size="22" color="#333"></u-icon>
				<text class="icon-text">店铺</text>
			</view> -->
			<view class="icon-item" @click="onCart">
				<u-icon name="shopping-cart-fill" size="22" color="#333"></u-icon>
				<text class="icon-text">购物车</text>
				<!-- 购物车数量徽章 -->
				<view v-if="totalQuantity > 0" class="cart-badge">
					<text class="badge-text">{{ totalQuantity > 99 ? '99+' : totalQuantity }}</text>
				</view>
			</view>
		</view>

		<!-- 右边按钮 -->
		<view class="right-btns">
			<!-- <u-button type="error" text="加入购物车" shape="circle" customStyle="flex:1;height:80rpx;margin-right:20rpx;background:#f04400;" @click="onAddCart" /> -->
			<u-button type="warning" text="去结算" shape="circle" customStyle="flex:1;height:80rpx;background:#ff7700;" @click="onBuyNow" />
		</view>
	</view>

	<!-- 购物车弹窗 -->
	<u-popup :show="showCartPopup" mode="bottom" :round="20" :closeable="true" @close="showCartPopup = false">
		<view class="cart-popup">
			<!-- 弹窗标题 -->
			<view class="popup-header">
				<view class="header-left">
					<text class="popup-title">购物车</text>
					<text class="popup-subtitle">共{{ totalQuantity }}件商品</text>
				</view>
				<view class="header-right" v-if="cartItems.length > 0">
					<u-button text="清空" size="mini" type="error" plain @click="onClearCart" />
				</view>
			</view>

			<!-- 购物车商品列表 -->
			<scroll-view class="cart-list" scroll-y="true" v-if="cartItems.length > 0">
				<view class="cart-item" v-for="item in cartItems" :key="item.id">
					<!-- 商品图片 -->
					<view class="item-image">
						<u-image :src="item.image" width="80rpx" height="80rpx" radius="8rpx"></u-image>
					</view>
					<!-- 商品信息 -->
					<view class="item-info">
						<text class="item-title">{{ item.title }}</text>
						<text class="item-desc" v-if="item.desc">{{ item.desc }}</text>
						<view class="item-bottom">
							<view class="item-price">
								<text class="price-symbol">￥</text>
								<text class="price-value">{{ item.price }}</text>
							</view>
							<view class="item-quantity">
								<view class="quantity-btn minus-btn" @click="onDelQuantity(item)">
									<u-icon name="minus-circle-fill" size="20" color="#666"></u-icon>
								</view>
								<u-number-box 
									v-model="item.num" 
									:min="0" 
									:max="99"
									size="small"
									@change="onCartQuantityChange(item)"
									:show-minus="false"
									:show-plus="false"
								>
									<!-- <template #minus>
										<view class="quantity-btn minus-btn" @click="onDelQuantity(item)">
											<u-icon name="minus-circle-fill" size="20" color="#666"></u-icon>
										</view>
									</template> -->
									<template #input>
										<text class="quantity-input">{{ item.num }}</text>
									</template>
									<!-- <template #plus>
										<view class="quantity-btn plus-btn" @click="onAddQuantity(item)">
											<u-icon name="plus-circle-fill" size="20" color="#f00"></u-icon>
										</view>
									</template> -->
								</u-number-box>
								<view class="quantity-btn plus-btn" @click="onAddQuantity(item)">
									<u-icon name="plus-circle-fill" size="20" color="#f00"></u-icon>
								</view>
								<view class="delete-btn" @click="onDeleteItem(item)">
									<u-icon name="trash" size="20" color="#ff4757"></u-icon>
								</view>
							</view>
						</view>
					</view>
				</view>
			</scroll-view>

			<!-- 空购物车状态 -->
			<view class="empty-cart" v-else>
				<u-icon name="shopping-cart" size="80" color="#ccc"></u-icon>
				<text class="empty-text">购物车是空的</text>
			</view>

			<!-- 底部操作栏 -->
			<view class="popup-footer" v-if="cartItems.length > 0">
				<view class="total-info">
					<text class="total-label">合计：</text>
					<text class="total-price">￥{{ totalPrice.toFixed(2) }}</text>
				</view>
				<!-- <view class="footer-btns">
					<u-button text="清空" size="small" type="info" plain @click="onClearCart" />
					<u-button text="去结算" size="small" type="primary" @click="onCheckout" />
				</view> -->
			</view>
		</view>
	</u-popup>
</template>

<script setup lang="ts">
import { ref, computed, toRaw, defineEmits, defineProps, nextTick } from 'vue'
import { globalCart, type CartItem } from '@/composables/useCart'
import { cartAddFun, cartListFun, cartClearFun, cartDeleteFun, cartEditFun } from '@/api/port'

/**
 * 组件属性接口
 */
interface Props {
  /** 当前选中的商品信息（用于加入购物车和立即购买） */
  currentProduct?: {
    id: string | number
    title: string
    price: number
    image: string
    desc?: string
  }
}

/**
 * 组件事件接口
 */
interface Emits {
  /** 立即购买事件 */
  (e: 'buyNow', productIds: string): void
  /** 加入购物车事件 */
  (e: 'addToCart', product: any): void
}

// const props = withDefaults(defineProps<Props>(), {})
const props = defineProps({
	currentProduct: {
		type: Array,
		default: () => ([])
	}
})
const emit = defineEmits<Emits>()

// 购物车弹窗显示状态
const showCartPopup = ref(false)

// 使用全局购物车状态
const { 
  cartItems, 
  totalQuantity, 
  totalPrice, 
  addToCart, 
  updateQuantity, 
  clearCart, 
  getCartItemIds 
} = globalCart

/**
 * 联系客服事件处理
 */
const onService = () => {
  // 这里可以集成客服功能
  uni.showToast({ title: '联系客服' })
}

/**
 * 进入店铺事件处理
 */
const onShop = () => {
  // 这里可以跳转到店铺首页
  uni.showToast({ title: '进入店铺' })
}

/**
 * 打开购物车弹窗
 */
const onCart = () => {
  showCartPopup.value = true
}

/**
 * 加入购物车事件处理
 */
const onAddCart = () => {
	console.log('props===========================',props)
	console.log('props as plain object:', JSON.parse(JSON.stringify(props)))
  if (!props.currentProduct) {
    uni.showToast({
      title: '请选择商品',
      icon: 'none'
    })
    return
  }

  // 获取商品数量，默认为1
//   const quantity = (props.value.currentProduct as any).quantity || 1
  
//   if (quantity <= 0) {
//     uni.showToast({
//       title: '请选择商品数量',
//       icon: 'none'
//     })
//     return
//   }

  // 添加商品到购物车
  props.currentProduct.forEach((item: any) => {
    addToCart({
      id: item.id,
      title: item.title,
      price: item.price,
      image: item.image,
      desc: item.desc
    }, item.num)
  })

  // 触发父组件事件
//   emit('addToCart', props.currentProduct)
}

/**
 * 立即购买事件处理
 */
const onBuyNow = () => {
  if (cartItems.value.length === 0) {
    uni.showToast({
      title: '购物车为空',
      icon: 'none'
    })
    return
  }

  // 获取购物车商品ID列表
  const productIds = getCartItemIds()
  
  // 触发父组件事件，传递商品ID字符串
  emit('buyNow', productIds)
  
  uni.showToast({
    title: `立即购买: ${productIds}`,
    icon: 'none'
  })
}

/**
 * 购物车商品数量变化处理
 * @param item 购物车商品项
 */
const onCartQuantityChange = (item: CartItem) => {
	console.log('item', item)
  
}

// 增加数量
const onAddQuantity = async (item: CartItem) => {
	console.log('item', item)
	// 调用添加购物车接口
	await cartAddFun({
		goods_id: item.goods_id,
		num: 1
	})
	console.log('成功调用添加购物车接口:', item.title, '增加数量:', 1)

	// 刷新购物车数据
	await cartListFun().then(res=>{
		if(res.code == 1){
			cartItems.value = res.data
		}
	})
	emit('updateCartList', item, 'plus')
}

/**
 * 删除单个商品
 * @param item 要删除的商品项
 */
const onDeleteItem = (item: CartItem) => {
  uni.showModal({
    title: '确认删除',
    content: `确定要删除 ${item.title} 吗？`,
    success: async (res) => {
      if (res.confirm) {
        // 从购物车中移除该商品
		await cartDeleteFun({
			id: item.id
		}).then(async res=>{
			if(res.code == 1){
				uni.showToast({
					title: '删除成功',
					icon: 'success'
				})
				// 刷新购物车数据
				await cartListFun().then(res=>{
					if(res.code == 1){
						cartItems.value = res.data
					}
				})
				emit('updateCartList', item, 'del')
			}
		})
      }
    }
  })
}

/**
 * 清空购物车
 */
const onClearCart = async () => {
  uni.showModal({
    title: '确认清空',
    content: '确定要清空购物车吗？',
    success: async (res) => {
      if (res.confirm) {
        await cartClearFun()
        uni.showToast({
          title: '购物车已清空',
          icon: 'success'
        })
		await cartListFun().then(res=>{
			if(res.code == 1){
				cartItems.value = res.data
			}
		})
		emit('clearCartList')
      }
    }
  })
}

/**
 * 去结算
 */
const onCheckout = () => {
  const productIds = getCartItemIds()
  emit('buyNow', productIds)
  showCartPopup.value = false
  
  uni.showToast({
    title: `去结算: ${productIds}`,
    icon: 'none'
  })
}
/**
 * 删除数量
 * @param item 购物车商品项
 */
const onDelQuantity = async (item: any) => {
	// 将Proxy对象转换为普通对象
	const rawItem = toRaw(item)
	console.log('删除数量:', rawItem)
	if(rawItem.num <= 0){
		return
	}
	await nextTick()
	
	// 如果数量为1，则删除该商品
	if(rawItem.num == 1) {
		// 调用删除购物车接口
		const res = await cartDeleteFun({
			id: rawItem.id
		})
		if(res.code == 1){
			emit('updateCartList', item, 'minus')
			// 从购物车数组中删除该商品
			cartItems.value = cartItems.value.filter((cartItem: any) => cartItem.id !== rawItem.id)
		}
	} else {
		// 调用编辑购物车接口，减少数量
		const res = await cartEditFun({
			id: rawItem.id,
			num: rawItem.num - 1
		})
		if(res.code == 1){
			emit('updateCartList', item, 'minus')
			cartItems.value.forEach((item: any) => {
				if (item.id == rawItem.id) {
					item.num = rawItem.num - 1
				}
			})
		}
	}
}
/**
 * 暴露给父组件的方法
 */
defineExpose({
  /** 打开购物车弹窗 */
  openCart: () => {
    showCartPopup.value = true
  },
  /** 关闭购物车弹窗 */
  closeCart: () => {
    showCartPopup.value = false
  }
})
</script>

<style scoped>
.bottom-bar {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	height: 100rpx;
	background: #fff;
	display: flex;
	align-items: center;
	border-top: 1rpx solid #eee;
	z-index: 1000;
}

.left-icons {
	flex: 1;
	display: flex;
	justify-content: space-around;
	align-items: center;
}

.icon-item {
	display: flex;
	flex-direction: column;
	align-items: center;
	font-size: 22rpx;
	color: #333;
	position: relative;
}

.icon-text {
	margin-top: 6rpx;
	font-size: 22rpx;
}

.right-btns {
	flex: 3;
	display: flex;
	justify-content: flex-end;
	padding: 0 20rpx;
}

.cart-badge {
	position: absolute;
	top: -8rpx;
	right: -8rpx;
	min-width: 32rpx;
	height: 32rpx;
	background-color: #ff4757;
	border-radius: 16rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 0 8rpx;
}

.badge-text {
	font-size: 20rpx;
	color: #fff;
	font-weight: 500;
	line-height: 1;
}

.cart-popup {
	width: 100%;
	max-height: 80vh;
	background-color: #fff;
	display: flex;
	flex-direction: column;
}

.popup-header {
	padding: 32rpx 84rpx 24rpx 32rpx;
	border-bottom: 1rpx solid #f5f5f5;
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.header-left {
	display: flex;
	flex-direction: column;
	gap: 8rpx;
}

.header-right {
	flex-shrink: 0;
}

.popup-title {
	font-size: 32rpx;
	font-weight: 600;
	color: #333;
}

.popup-subtitle {
	font-size: 24rpx;
	color: #999;
}

.cart-list {
	flex: 1;
	width: 100%;
	max-height: 50vh;
	padding: 0 32rpx;
	box-sizing: border-box;
}

.cart-item {
	display: flex;
	align-items: flex-start;
	padding: 24rpx 0;
	border-bottom: 1rpx solid #f5f5f5;
	gap: 24rpx;
}

.cart-item:last-child {
	border-bottom: none;
}

.item-image {
	flex-shrink: 0;
}

.item-info {
	flex: 1;
	display: flex;
	flex-direction: column;
	gap: 8rpx;
}

.item-title {
	font-size: 28rpx;
	font-weight: 500;
	color: #333;
	line-height: 1.4;
	display: -webkit-box;
	-webkit-box-orient: vertical;
	-webkit-line-clamp: 2;
	overflow: hidden;
}

.item-desc {
	font-size: 24rpx;
	color: #999;
	line-height: 1.3;
	display: -webkit-box;
	-webkit-box-orient: vertical;
	-webkit-line-clamp: 1;
	overflow: hidden;
}

.item-bottom {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-top: 16rpx;
}

.item-price {
	display: flex;
	align-items: baseline;
}

.price-symbol {
	font-size: 20rpx;
	color: #ff4757;
	font-weight: 500;
}

.price-value {
	font-size: 28rpx;
	color: #ff4757;
	font-weight: 600;
	margin-left: 2rpx;
}

.item-quantity .quantity-btn {
	width: 40rpx;
	height: 40rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.item-quantity {
	display: flex;
	align-items: center;
	gap: 16rpx;
}

.item-quantity .quantity-input {
	width: 50rpx;
	height: 40rpx;
	text-align: center;
	line-height: 40rpx;
	font-size: 24rpx;
	color: #333;
}

.delete-btn {
	width: 40rpx;
	height: 40rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	border-radius: 50%;
	transition: background-color 0.2s;
}

.delete-btn:active {
	background-color: rgba(255, 71, 87, 0.1);
}

.empty-cart {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 80rpx 32rpx;
	gap: 24rpx;
}

.empty-text {
	font-size: 28rpx;
	color: #999;
}

.popup-footer {
	padding: 24rpx 32rpx 32rpx;
	border-top: 1rpx solid #f5f5f5;
	display: flex;
	justify-content: space-between;
	align-items: center;
	gap: 24rpx;
}

.total-info {
	display: flex;
	align-items: baseline;
	gap: 8rpx;
}

.total-label {
	font-size: 28rpx;
	color: #333;
	font-weight: 500;
}

.total-price {
	font-size: 32rpx;
	color: #ff4757;
	font-weight: 600;
}

.footer-btns {
	display: flex;
	gap: 16rpx;
}
</style>
